<?php

?>
<style>
    .load-photo {display: block;}
    .delete-photo {display: none;}
    
    .photo_exists .load-photo {display: none;}
    .photo_exists .delete-photo {display: block;}
</style>
<div class="hidden" id="editUser-cont">
    <form class="well form-inline margin-horisontal" action="" method="POST" name="editUserForm" id="editUserForm">
        <fieldset>

            <input type="hidden" name="action" id="action" value="<?php echo ACTIONS::USERS_UPDATE_USER; ?>">
            <input type="hidden" id="f_user_id" name="f_user_id" value="<?php echo Arr::getValue($params, 'f_user_id', 0); ?>">

            
            <div class="pull-right">
                <div class="control-group" id="cg-f_user_organisation">
                    <label class="control-label" for="f_user_organisation">Место работы</label>
                    <div class="controls">
                        <input type="text" class="input-large" id="f_user_organisation" name="f_user_organisation" value="<?php echo Arr::getValue($params, 'f_user_organisation', ''); ?>">
                    </div>
                    <span class="help-inline"></span>
                </div>
                
                <div class="control-group" id="cg-f_user_job_position">
                    <label class="control-label" for="f_user_job_position">Профессия</label>
                    <div class="controls">
                        <input type="text" class="input-large" id="f_user_job_position" name="f_user_job_position" value="<?php echo Arr::getValue($params, 'f_user_job_position', ''); ?>">
                    </div>
                    <span class="help-inline"></span>
                </div>

                <div class="control-group" id="cg-f_user_email">
                    <label class="control-label" for="f_user_email">E-mail</label>
                    <div class="controls">
                        <input type="text" class="input-large" id="f_user_email" name="f_user_email" value="<?php echo Arr::getValue($params, 'f_user_email', ''); ?>">
                    </div>
                    <span class="help-inline"></span>
                </div>

                <div class="control-group" id="cg-f_user_phone">
                    <label class="control-label" for="f_user_phone">Телефон</label>
                    <div class="controls">
                        <input type="text" class="input-large" id="f_user_phone" name="f_user_phone" value="<?php echo Arr::getValue($params, 'f_user_phone', ''); ?>">
                    </div>
                    <span class="help-inline"></span>
                </div>

                <div class="control-group" id="cg-f_user_newpassword">
                    <label class="control-label" for="f_user_newpassword">Пароль</label>
                    <div class="controls">
                        <input type="text" class="input-large" id="f_user_newpassword" name="f_user_newpassword" value="">
                    </div>
                    <span class="help-inline"></span>
                    <div style="font-size: 10px; line-height: 12px;">Оставьте поле "Пароль" пустым, <br>если не будете изменять пароль</div>
                    
                </div>
            </div>
            
            
            
            
            <div>
                <div id="editUserPhotoAndName"></div>
                <div id="editUserPhotoEdit-cont" class="" style="padding: 10px 0px 0px 5px;">
                    <button class="load-photo btn btn-primary">Загрузить фото</button>
                    <button class="delete-photo btn btn-danger">Удалить фото</button>
                </div>
            </div>
            
            <div>       
                <div class="control-group hidden" id="cg-f_user_first_name">
                    <label class="control-label" for="f_user_first_name">Имя</label>
                    <div class="controls">
                        <input type="text" class="input-large" readonly="readonly" id="f_user_first_name" name="f_user_first_name" value="<?php echo Arr::getValue($params, 'f_user_first_name', ''); ?>">
                    </div>
                    <span class="help-inline"></span>
                </div>

                <div class="control-group hidden" id="cg-f_user_last_name">
                    <label class="control-label" for="f_user_last_name">Фамилия</label>
                    <div class="controls">
                        <input type="text" class="input-large" readonly="readonly" id="f_user_last_name" name="f_user_last_name" value="<?php echo Arr::getValue($params, 'f_user_last_name', ''); ?>">
                    </div>
                    <span class="help-inline"></span>
                </div>

                <div class="control-group hidden" id="cg-f_user_login">
                    <label class="control-label" for="f_user_login">Логин</label>
                    <div class="controls">
                        <input type="text" class="input-large" readonly="readonly" id="f_user_login" name="f_user_login" value="<?php echo Arr::getValue($params, 'f_user_login', ''); ?>">
                    </div>
                    <span class="help-inline"></span>
                </div>
                
            </div>
            
            
            <div class="clear_both"></div>
            <div class="form-actions" style="text-align: right;">
                <button type="submit" class="btn btn-primary" id="editUser-submit"><i class="icon-ok icon-white"></i> Сохранить</button>
                <button type="reset" class="btn btn-danger" id="editUser-cancel"><i class="icon-remove icon-white"></i> Отменить</button>
            </div>
        </fieldset>
    </form>
</div>

<div class="hidden" id="editUser-templates">
    
    <div id="editUser-userInfo-tmpl">
        <div class="userphoto-container pull-left" title="{%login%}">
            <img src="<?php echo APP_HTML_DEF_AVA; ?>" data-src="{%photo%}" alt="{%login%}" class="userphoto-image">
        </div>

        <div class="userinfo-fio nowrap">{%last_name%}</div>
        <div class="userinfo-fio nowrap">{%first_name%}</div>
        <div class="userinfo-otherinfo nowrap">{%login%}</div>
        <div style="clear:left"></div>
    </div>
    
    
    
    
<script>

     function editUserWrongFields(wf) {
        wf = wf || {};
        var wf_count = 0;

        var cgdivs = Elm.editUserForm.find('div.error').removeClass('error');
        cgdivs.find('span.help-inline').empty();

        for(var id in wf) {
            if (!wf.hasOwnProperty(id)) continue;
            var msg = wf[id];

            var cg = $('#cg-f_user_'+id).addClass('error');
            cg.find('span.help-inline').html(msg);
            wf_count++;
        }
        return wf_count;
    }
    
    
    function editUserGetUserInfo(id, callback) {
        id = id || 0;
        var tf = function() {};
        callback = callback || tf;
        if (typeof(callback) != 'function') callback = tf;
        if (Elm.hasOwnProperty('Users') && Elm.Users.hasOwnProperty(id)) {
            callback(Elm.Users[id]);
        }
        else {
            var send = {
                action: '<?php echo ACTIONS::USERS_GET_ACCESS_INFO; ?>',
                users: [id]
            };
            
            requestUserInfo(send, callback);
        }
    }
    
    function editUserRequestUserInfo(send, callback) {
        callback = callback || function() {};
        jsonRequest(
            'users.php',
            send,

            function(data) {
                if(!checkSession(data)) {
                    Elm.loginFormModal.dialog('open');
                    Elm.loginFormModal.successCallback = function(){
                        requestUserInfo(send, callback);
                    };
                    return;
                }
                if (!data.state) {
                    uiAlert(data.message,'Error');
                    return;
                }
                
                if (data.hasOwnProperty('response_data') && data.response_data) {
                    var resp = data.response_data;
                    if (resp.hasOwnProperty('usersData') && resp.usersData.hasOwnProperty(userId)) {
                        var user = resp.usersData[id];
                        Elm.Users[id] = user;
                        callback(user);
                    }
                    else uiAlert('Пользователь не найден','Error');
                }
            },
            
            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );
    }
    
    
    function editUserFormFill(userdata) {
        userdata = userdata || {};
        var inp;
        
        for(var i in userdata) {
            if (userdata.hasOwnProperty(i)) {
                inp = $('#f_user_'+i);
                if (inp.length) inp.val(userdata[i]);
            }
        }
        $('#f_user_newpassword').val('');
        
        userEditUserInfoRefresh(userdata);
    } 
    
    
    
    function editUserDialogOpen(id, onSuccess, onPhotoChange) {
        onSuccess       = onSuccess || function() {};
        onPhotoChange   = onPhotoChange || function() {};
        
        editUserGetUserInfo(id, function(userdata) {
            editUserFormFill(userdata);
            if (Elm.hasOwnProperty('editUser') && Elm.editUser) Elm.editUser.dialog('open');
            Elm.editUserForm.successCallback = onSuccess;
            Elm.editUserForm.onPhotoChange = onPhotoChange;
        });
    }
    
    
    function editUserDialogClose() {
        Elm.editUserForm.successCallback = function() {};
        Elm.editUserForm.onPhotoChange = function(){};
        Elm.editUser.dialog('close');
    }
    
    
    
    function editUserSubmit() {
        editUserWrongFields({});
        var send = Elm.editUserForm.serialize();
        jsonRequest(
            'users.php',
            send,

            function(data) {
                editUserWrongFields({});
                if(checkSession(data)) {
                    if (!data.state) {
                        uiAlert(data.message,'Error');
                        return;
                    }

                    if (data.hasOwnProperty('response_data') && data.response_data) {
                        var resp = data.response_data;
                        if (resp.hasOwnProperty('wrongFields')) {
                            var wf = editUserWrongFields(resp.wrongFields);
                            if (wf*1>0) return;
                        }

                        if (resp.hasOwnProperty('insertedId')) {
                            if (
                                Elm.editUserForm.hasOwnProperty('successCallback')
                                && (typeof(Elm.editUserForm.successCallback) == 'function')
                            ) {
                                var cdata;
                                if (data.hasOwnProperty('request_data') && data.request_data) cdata = data.request_data;
                                else cdata = {};
                                
                                $.extend(cdata, resp);
                                if (cdata.hasOwnProperty('user')) {
                                    Elm.Users[cdata.user.id] = cdata.user;
                                }
                                var cb = Elm.editUserForm.successCallback;
                                Elm.editUserForm.successCallback = function() {};
                                cb(cdata);
                            }
                        }
                    }
                    Elm.editUser.dialog('close');
                }
                else {
                    Elm.loginFormModal.dialog('open');
                    Elm.loginFormModal.successCallback = function(){
                        editUserSubmit();
                    };
                }
            },

            function() {
                editUserWrongFields({});
                uiAlert('Ошибка соединения','Error');
            }
        );
        return false;
    }
    
    
    
    
    function userEditUserInfoRefresh(userdata) {
        Elm.editUserPhotoAndName.empty().html(
                fillTemplate(
                    '#editUser-userInfo-tmpl', 
                    $.extend( {}, userdata, {} )
                )
        );
        if (userdata.photo_exists) Elm.editUserPhotoEditCtrls.addClass('photo_exists');    
        else Elm.editUserPhotoEditCtrls.removeClass('photo_exists');  
        
        var img = Elm.editUserPhotoAndName.find('img.userphoto-image');
        img.attr('src', img.attr('data-src'));
        
        
    }
    
    

    function editUserPhotoBtnCallbacks() {
        Elm.editUserPhotoEditCtrls.find('.load-photo').click(function() {
            var id = $('#f_user_id').val();
            fileUploadDialogOpen (
                'users.php', 
                {
                    action: '<?php echo ACTIONS::USERS_LOAD_PHOTO; ?>',
                    id: id
                }, 
                //onSuccess
                function(data) {
                    if(checkSession(data)) {
                        if (!data.state) {
                            uiAlert(data.message,'Error');
                            return;
                        }
                        if (data.hasOwnProperty('response_data') && data.response_data) {
                            var resp = data.response_data;
                            if (resp.hasOwnProperty('ava')) {
                                Elm.Users[id].photo = resp.ava;
                                Elm.Users[id].photo_exists = 1;
                                
                                var cdata;
                                if (data.hasOwnProperty('request_data') && data.request_data) cdata = data.request_data;
                                else cdata = {};
                                $.extend(cdata, resp);
                                
                                var cb = Elm.editUserForm.onPhotoChange;
                                if (typeof(cb) == 'function') cb(cdata);
                                userEditUserInfoRefresh(Elm.Users[id]);
                                return;
                            }
                        }
                        uiAlert('Возникла ошибка, откройте страницу заново.','Error');
                    }
                    else {
                        Elm.loginFormModal.dialog('open');
                    }
                }, 
                //onError
                function(data) {
                    uiAlert('Ошибка соединения', 'Error');
                }
            );
            return false;
        });


        Elm.editUserPhotoEditCtrls.find('.delete-photo').click(function() {
            var id = $('#f_user_id').val();
            var send = {
                id: id,
                action: '<?php echo ACTIONS::USERS_DELETE_PHOTO; ?>'
            };

            showLoader();
            jsonRequest(
                'users.php',
                send,
                
                function(data){
                    if(checkSession(data)) {
                        if (!data.state) {
                            uiAlert(data.message,'Error');
                            return;
                        }
                        if (data.hasOwnProperty('response_data') && data.response_data) {
                            var resp = data.response_data;
                            if (resp.hasOwnProperty('ava')) {
                                Elm.Users[id].photo = resp.ava;
                                Elm.Users[id].photo_exists = 0;
                                
                                var cdata;
                                if (data.hasOwnProperty('request_data') && data.request_data) cdata = data.request_data;
                                else cdata = {};
                                $.extend(cdata, resp);
                                
                                var cb = Elm.editUserForm.onPhotoChange;
                                if (typeof(cb) == 'function') cb(cdata);
                                userEditUserInfoRefresh(Elm.Users[id]);
                                return;
                            }
                        }
                        uiAlert('Возникла ошибка, откройте страницу заново.','Error');
                    }
                    else {
                        Elm.loginFormModal.dialog('open');
                    }
                },
                
                function(){
                    uiAlert('Ошибка соединения', 'Error');
                }
            );
            return false;
        });
    }
    
    
    
    

    $(function() {
        Elm.editUser = $('#editUser-cont');
        Elm.editUserForm = $('#editUserForm');
        Elm.editUserPhotoAndName = $('#editUserPhotoAndName');
        Elm.editUserPhotoEditCtrls = $('#editUserPhotoEdit-cont');
        Elm.editUserForm.successCallback = function(data) {};
        Elm.editUserForm.onPhotoChange = function(data) {};

        $('#editUser-cancel').click(function(){
            editUserDialogClose();
            return false;
        });

        Elm.editUser.dialog({
            width       : 600,
            modal       : true,
            resizable   : false,
            title       : "Редактировать аккаунт",
            autoOpen    : false,
            buttons     : {}
        }).removeClass('hidden');


        


        Elm.editUserForm.submit(function(){
            editUserSubmit();
            return false;
        });
        
        
        
        
        editUserPhotoBtnCallbacks();



    });




</script>